﻿Imports System.Net
Imports System.IO
Imports System.Text
Imports System.Collections.Specialized

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Dim filepath As String = IO.Path.Combine(Application.StartupPath, "filename.ext")
        Dim filepath = "d:\P1.jpg"
        Dim url As String = "http://www.extremesurvival.co.za/ucs/Submit.php"

        Dim boundary As String = IO.Path.GetRandomFileName
        Dim header As New System.Text.StringBuilder()

        header.Append("--" & boundary)
        'form-data;name="key"
        header.Append("Content-Disposition: form-data; name=""username"";")
        header.AppendLine()
        header.Append("Merrick")
        header.AppendLine()

        header.AppendLine("--" & boundary)
        header.Append("Content-Disposition: form-data; name=""userfile"";")
        header.AppendFormat("filename=""{0}""", IO.Path.GetFileName(filepath))
        header.AppendLine()
        header.AppendLine("Content-Type: application/octet-stream")
        header.AppendLine()

        Dim headerbytes() As Byte = System.Text.Encoding.UTF8.GetBytes(header.ToString)
        Dim endboundarybytes() As Byte = System.Text.Encoding.ASCII.GetBytes(vbNewLine & "--" & boundary & "--" & vbNewLine)

        Dim req As Net.HttpWebRequest = Net.HttpWebRequest.Create(url)
        req.ContentType = "multipart/form-data; boundary=" & boundary
        req.ContentLength = headerbytes.Length + New IO.FileInfo(filepath).Length + endboundarybytes.Length
        req.Method = "POST"

        Dim s As IO.Stream = req.GetRequestStream
        s.Write(headerbytes, 0, headerbytes.Length)
        Dim filebytes() As Byte = My.Computer.FileSystem.ReadAllBytes(filepath)
        s.Write(filebytes, 0, filebytes.Length)
        s.Write(endboundarybytes, 0, endboundarybytes.Length)
        s.Close()
    End Sub

    Public Shared Function UploadFileEx(ByVal uploadfile As String, ByVal url As String, ByVal fileFormName As String, ByVal contenttype As String, ByVal querystring As NameValueCollection, ByVal cookies As CookieContainer) As String
        If (fileFormName Is Nothing) OrElse (fileFormName.Length = 0) Then
            fileFormName = "file"
        End If

        If (contenttype Is Nothing) OrElse (contenttype.Length = 0) Then
            contenttype = "application/octet-stream"
        End If


        Dim postdata As String
        postdata = "?"
        If querystring IsNot Nothing Then
            For Each key As String In querystring.Keys
                postdata += key & "=" & querystring.[Get](key) & "&"
            Next
        End If
        Dim uri As New Uri(url & postdata)


        Dim boundary As String = "----------" & DateTime.Now.Ticks.ToString("x")
        Dim webrequest__1 As HttpWebRequest = DirectCast(WebRequest.Create(uri), HttpWebRequest)
        webrequest__1.CookieContainer = cookies
        webrequest__1.ContentType = "multipart/form-data; boundary=" & boundary
        webrequest__1.Method = "POST"


        ' Build up the post message header
        Dim sb As New StringBuilder()
        sb.Append("--")
        sb.Append(boundary)
        sb.Append(vbCr & vbLf)
        sb.Append("Content-Disposition: form-data; name=""")
        sb.Append(fileFormName)
        sb.Append("""; filename=""")
        sb.Append(Path.GetFileName(uploadfile))
        sb.Append("""")
        sb.Append(vbCr & vbLf)
        sb.Append("Content-Type: ")
        sb.Append(contenttype)
        sb.Append(vbCr & vbLf)
        sb.Append(vbCr & vbLf)

        Dim postHeader As String = sb.ToString()
        Dim postHeaderBytes As Byte() = Encoding.UTF8.GetBytes(postHeader)

        ' Build the trailing boundary string as a byte array
        ' ensuring the boundary appears on a line by itself
        Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(vbCr & vbLf & "--" & boundary & vbCr & vbLf)

        Dim fileStream As New FileStream(uploadfile, FileMode.Open, FileAccess.Read)
        Dim length As Long = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length
        webrequest__1.ContentLength = length

        Dim requestStream As Stream = webrequest__1.GetRequestStream()

        ' Write out our post header
        requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length)

        ' Write out the file contents
        Dim buffer As Byte() = New [Byte](CUInt(Math.Min(4096, CInt(fileStream.Length))) - 1) {}
        Dim bytesRead As Integer = 0
        While (InlineAssignHelper(bytesRead, fileStream.Read(buffer, 0, buffer.Length))) <> 0
            requestStream.Write(buffer, 0, bytesRead)
        End While

        ' Write out the trailing boundary
        requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
        Dim responce As WebResponse = webrequest__1.GetResponse()
        Dim s As Stream = responce.GetResponseStream()
        Dim sr As New StreamReader(s)

        Return sr.ReadToEnd()
    End Function
    Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
        target = value
        Return value
    End Function

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim cookies As New CookieContainer()
        'add or use cookies
        Dim querystring As New NameValueCollection()
        querystring("username") = "merrick"
        querystring("password") = "snake3"
        Dim uploadfile As String
        ' set to file to upload
        uploadfile = "d:\p1.jpg"

        'everything except upload file and url can be left blank if needed
        Dim outdata As String = UploadFileEx(uploadfile, "http://www.extremesurvival.co.za/ucs/Submit.php", "userfile", "image/jpeg", querystring, cookies)
    End Sub
    Private Function UploadFileExB(ByVal FileName As String, ByVal URL As String, ByVal FileFormName As String, ByVal ContentType As String, ByVal QueryStringArguments As Dictionary(Of String, String), ByVal Cookies As Net.CookieContainer) As String

        If FileFormName = "" Then FileFormName = "file"
        If ContentType = "" Then ContentType = "application/octet-stream"

        Dim PostData As String = "?"
        If QueryStringArguments IsNot Nothing Then
            For Each kvp As KeyValuePair(Of String, String) In QueryStringArguments
                PostData &= kvp.Key & "=" & kvp.Value & "&"
            Next
        End If


        Dim URI As New Uri(URL + PostData)
        Dim Boundary As String = "----------" + DateTime.Now.Ticks.ToString("x")
        Dim WReq As Net.HttpWebRequest = DirectCast(Net.WebRequest.Create(URI), Net.HttpWebRequest)
        WReq.CookieContainer = Cookies
        WReq.ContentType = "multipart/form-data; boundary=" + Boundary
        WReq.Method = "POST"

        Dim PostHeader As String = String.Format("--" & Boundary & "{0}" & _
        "Content-Disposition: form-data; name=""" & FileFormName _
        & """; filename=""" & IO.Path.GetFileName(FileName) & """{0}" _
        & "Content-Type: " & ContentType & "{0}{0}", vbNewLine)

        Dim PostHeaderBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(PostHeader)
        Dim BoundaryBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(vbNewLine & "--" + Boundary + vbNewLine)

        Dim FileStream As New IO.FileStream(FileName, IO.FileMode.Open, IO.FileAccess.Read)

        WReq.ContentLength = PostHeaderBytes.Length + FileStream.Length + BoundaryBytes.Length

        Dim RequestStream As IO.Stream = WReq.GetRequestStream()
        RequestStream.Write(PostHeaderBytes, 0, PostHeaderBytes.Length)
        Dim buffer As Byte() = New Byte(CInt(Math.Min(4096, CInt(FileStream.Length))) - 1) {}
        Dim bytesRead As Integer = 0
        Do
            bytesRead = FileStream.Read(buffer, 0, buffer.Length)
            If bytesRead = 0 Then Exit Do
            RequestStream.Write(buffer, 0, bytesRead)
        Loop
        RequestStream.Write(BoundaryBytes, 0, BoundaryBytes.Length)

        Dim Rta As Net.WebResponse = WReq.GetResponse()
        Dim s As IO.Stream = Rta.GetResponseStream()
        Dim sr As New IO.StreamReader(s)

        Return sr.ReadToEnd()
    End Function
    Public Sub UploadFile(ByVal FileName As String)
        Dim OldValue As Boolean = System.Net.ServicePointManager.Expect100Continue

        Try

            System.Net.ServicePointManager.Expect100Continue = False
            '1. Cookie
            Dim Cookie As New Net.CookieContainer()

            '2. Arguments
            Dim QueryStringArguments As New Dictionary(Of String, String)
            QueryStringArguments.Add("username", "mer03")
            QueryStringArguments.Add("password", "jojoern")
            QueryStringArguments.Add("imageid", "img01")

            '3. contentType
            Dim ContentType As String = ""
            Select Case IO.Path.GetExtension(FileName).ToLower
                Case ".jpg"
                    ContentType = "image/jpeg"
                Case ".jpeg"
                    ContentType = "image/jpeg"
                Case ".gif"
                    ContentType = "image/gif"
                Case ".png"
                    ContentType = "image/png"
                Case ".bmp"
                    ContentType = "image/bmp"
                Case ".tif"
                    ContentType = "image/tiff"
                Case ".tiff"
                    ContentType = "image/tiff"
                Case Else
                    ContentType = "image/unknown"
            End Select

            '4. Upload and return Rta
            UploadFileExB(FileName, "http://www.extremesurvival.co.za/ucs/Submit.php", "fileupload", ContentType, QueryStringArguments, Cookie)
        Catch ex As Exception
        Finally
            System.Net.ServicePointManager.Expect100Continue = OldValue
        End Try
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        UploadFile("d:\p1.jpg")
    End Sub
End Class
